<?php
declare(strict_types=1);

namespace Modules\LessonHour\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Illuminate\Support\Facades\DB;
use Modules\Customer\Models\Customer;
use Modules\CustomerLesson\Models\CustomerLesson;
use Modules\Develop\Support\Generate\Create\Request;
use Modules\LessonHour\Models\LessonHour;
use Modules\LessonHour\Http\Requests\LessonHourRequest;
use Modules\Teacher\Models\Teacher;
use Modules\User\Models\User;


class LessonHourController extends Controller
{
    public function __construct(
        protected readonly LessonHour $model
    ){}

    /**
     * @param LessonHourRequest $request
     * @return mixed
     */
    public function index(LessonHourRequest $request): mixed
    {
        $where = [];
        $param = $request->all();

        if (!empty($param['user_id']))
        {
            $where['lesson_hour.customer_id'] = $param['user_id'];
        }
        if (!empty($param['teacher_id']))
        {
            $where['lesson_hour.teacher_id'] = $param['teacher_id'];
        }
        if (!empty($param['lesson_type']))
        {
            $where['lesson_hour.lesson_type'] = $param['lesson_type'];
        }
        if (!empty($param['lesson_status']))
        {
            $where['lesson_hour.lesson_status'] = $param['lesson_status'];
        }

        $query = LessonHour::query()
            ->where($where);

        if (!empty($param['start_time']) && !empty($param['end_time']))
        {
            $query = $query->whereBetween("lesson_hour.created_at", [strtotime($param['start_time']), strtotime($param['end_time'])]);
        }

        return $query
            ->select(['lesson_hour.id','lesson_hour.lessons','lesson_hour.last_lessons','lesson_hour.lesson_type','lesson_hour.desc','lesson_hour.lesson_status','lesson_hour.remark','lesson_hour.created_at','teacher.name as teacher_name','customer.username as customer_name'])
            ->join("teacher","lesson_hour.teacher_id","=","teacher.id","left")
            ->join("customer","lesson_hour.customer_id","=","customer.id","left")
            ->orderByDesc("lesson_hour.created_at")
            ->paginate($param['limit'] ?? 10 ,['*'] ,'' ,$param['page'])->toArray();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function add(LessonHourRequest $request)
    {
        $param = $request->all();

        if (empty($param['user_id']) || empty($param['teacher_id']) || empty($param['lesson_type']) || empty($param['hour']) || empty($param['desc']))
        {
            throw new FailedException("课时信息必填");
        }

        $customerLesson = CustomerLesson::query()->where(['customer_id' => $param['user_id'], 'teacher_id' => $param['teacher_id']])->first();

        if ($param['lesson_type'] == self::LESSON_TYPE_3 && $customerLesson['lessons'] < $param['hour'])
        {
            throw new FailedException("剩余课时不足");
        }

        if (empty($customerLesson))
        {
            $customerLesson['customer_id'] = $param['user_id'];
            $customerLesson['teacher_id'] = $param['teacher_id'];
            $customerLesson['creator_id'] = $this->getLoginUser()['id'];
            $customerLesson['lessons'] = 0;
        }

        $customerLesson['lessons'] = $param['lesson_type'] == self::LESSON_TYPE_1 ? $customerLesson['lessons'] + $param['hour'] : $customerLesson['lessons'];

        // 开启事务
        DB::beginTransaction();

        try {
             if (empty($customerLesson['id']))
             {
                 (new CustomerLesson())->createBy($customerLesson);
             }else {
                 $customerLesson->save();
             }

            $lesson['customer_id'] = $param['user_id'];
            $lesson['teacher_id'] = $param['teacher_id'];
            $lesson['lesson_type'] = $param['lesson_type'];
            $lesson['lessons'] = $param['hour'];
            $lesson['last_lessons'] = $customerLesson['lessons']; // 课时剩余量
            $lesson['desc'] = $param['desc'];
            $lesson['remark'] = $param['remark'] ?? '';
            $lesson['pay_images'] = $param['pay_images'] ?? '';
            $lesson['lesson_status'] = $param['lesson_type'] == self::LESSON_TYPE_1 ? self::LESSON_STATUS_1 : self::LESSON_STATUS_2;
            $lesson['creator_id'] = $this->getLoginUser()['id'];
            $this->model->storeBy($lesson);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException("课时信息保存失败");
        }

        return "添加成功";
    }

    /**
     * 审核课时信息
     * @param LessonHourRequest $request
     * @return bool
     */
    public function check(LessonHourRequest $request)
    {
        $status = $request->get('status');
        $lessId = $request->get('id');
        $lesson = LessonHour::query()->where('id',$lessId)->first();
        $customerLesson = CustomerLesson::query()->where(['customer_id' => $lesson['customer_id'], 'teacher_id' => $lesson['teacher_id']])->first();

        if ($lesson['lesson_type'] == self::LESSON_TYPE_2)
        {
            if ($status == 1)
            {
                $lesson['lesson_status'] = self::LESSON_STATUS_1;
                $customerLesson['lessons'] = $customerLesson['lessons'] + $lesson['lessons'];
            }
            else
            {
                $lesson['lesson_status'] = self::LESSON_STATUS_4;
                $customerLesson['lessons'] = $customerLesson['lessons'] - $lesson['lessons'];
            }
        }
        elseif ($lesson['lesson_type'] == self::LESSON_TYPE_3)
        {
            if ($status == 1)
            {
                $lesson['lesson_status'] = self::LESSON_STATUS_5;
                $customerLesson['lessons'] = $customerLesson['lessons'] - $lesson['lessons'];
            }
            else
            {
                $lesson['lesson_status'] = self::LESSON_STATUS_4;
                $customerLesson['lessons'] = $customerLesson['lessons'] + $lesson['lessons'];
            }
        }

        if ($customerLesson['lessons'] < 0)
        {
            throw new FailedException("剩余课时不足");
        }

        if ($customerLesson->save())
        {
            $lesson['last_lessons'] = $customerLesson['lessons'];
            return $lesson->save();
        }

        throw new FailedException("课时信息审核失败");
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, LessonHourRequest $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        return $this->model->deleteBy($id);
    }


    public function lessonConfig()
    {
        return [
            'lessonType' => $this->lessonType(),
            'lessonStatus' => $this->lessonStatus(),
            'teacherList' => $this->teacherList(),
            'reservationStatus' => $this->reservationStatus(),
        ];
    }

    public function lessonType()
    {
        return [
            [
                "id" => self::LESSON_TYPE_1,
                "name" => "课时充值"
            ],
            [
                "id" => self::LESSON_TYPE_2,
                "name" => "额外赠课"
            ],
            [
                "id" => self::LESSON_TYPE_3,
                "name" => "额外扣除"
            ],
            [
                "id" => self::LESSON_TYPE_4,
                "name" => "预约课时"
            ]
        ];
    }

    public function lessonStatus()
    {
        return [
            [
                "id" => self::LESSON_STATUS_1,
                "name" => "已到账"
            ],
            [
                "id" => self::LESSON_STATUS_2,
                "name" => "审核中"
            ],
            [
                "id" => self::LESSON_STATUS_3,
                "name" => "冻结中"
            ],
            [
                "id" => self::LESSON_STATUS_4,
                "name" => "已驳回"
            ],
            [
                "id" => self::LESSON_STATUS_5,
                "name" => "已消费"
            ],
            [
                "id" => self::LESSON_STATUS_6,
                "name" => "已取消"
            ]
        ];
    }

    public function reservationStatus()
    {
        return [
            [
                "id" => self::RESERVATION_1,
                "name" => "未开始"
            ],
            [
                "id" => self::RESERVATION_2,
                "name" => "进行中"
            ],
            [
                "id" => self::RESERVATION_3,
                "name" => "已取消"
            ],
            [
                "id" => self::RESERVATION_4,
                "name" => "已完成"
            ]
        ];
    }

    public function customerList(LessonHourRequest $request)
    {
        $param = $request->all();
        if (!empty($param['teacher_id']))
        {
            return CustomerLesson::query()
                ->where('customer_lesson.teacher_id',$param['teacher_id'])
                ->join('customer','customer_lesson.customer_id','=','customer.id')
                ->select(['customer_lesson.customer_id as id','customer.username'])
                ->groupBy('customer_lesson.customer_id')->get();
        }
        return Customer::query()->where('status',1)->select(['id', 'username'])->get();
    }

    public function myCustomerList()
    {
        $logUser = $this->getLoginUser();
        $teacher = Teacher::query()->where('phone',$logUser['email'])->select(['id'])->first();

        return LessonHour::query()
            ->where('lesson_hour.teacher_id',$teacher['id'])
            ->join('customer','lesson_hour.customer_id','=','customer.id')
            ->select(['lesson_hour.customer_id as id','customer.username'])
            ->groupBy('lesson_hour.customer_id')->get();
    }

    public function teacherList()
    {
        $users = $this->getLoginUser();
        if ($users['id'] == 1)
        {
            return Teacher::query()->where('status',1)->select(['id', 'name'])->get();
        }
        else
        {
            return Teacher::query()->where('phone',$users['email'])->select(['id', 'name'])->get();
        }
    }

    // 课时类型
    const LESSON_TYPE_1 = 1; // 课时充值
    const LESSON_TYPE_2 = 2; // 额外赠课
    const LESSON_TYPE_3 = 3; // 额外扣除
    const LESSON_TYPE_4 = 4; // 预约课时

    // 课时状态
    const LESSON_STATUS_1 = 1; // 已到账
    const LESSON_STATUS_2 = 2; // 审核中
    const LESSON_STATUS_3 = 3; // 冻结中
    const LESSON_STATUS_4 = 4; // 已驳回
    const LESSON_STATUS_5 = 5; // 已消费
    const LESSON_STATUS_6 = 6; // 已取消

    // 预约课时状态
    const RESERVATION_1 = 1; // 未开始
    const RESERVATION_2 = 2; // 进行中
    const RESERVATION_3 = 3; // 已取消
    const RESERVATION_4 = 4; // 已完成

    //进课时的状态有 审核中 已到账  已驳回
    //用课的状态  冻结中  已消费 已取消
    //额外的 审核中 已消费 已驳回
}
